package com.firegod.group.service.impl;

import com.firegod.group.service.GroupService;
import com.firegod.servicebase.dao.CourseRepository;
import com.firegod.servicebase.dao.GroupRepository;
import com.firegod.servicebase.dao.TeacherRepository;
import com.firegod.servicebase.entity.Course;
import com.firegod.servicebase.entity.Group;
import com.firegod.servicebase.entity.Teacher;
import com.firegod.servicebase.exceptionhandler.exception.GuliException;
import com.firegod.shiro.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class GroupServiceImpl implements GroupService {

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private GroupRepository groupRepository;

    @Autowired
    private TeacherRepository teacherRepository;

    @Autowired
    private TokenService tokenService;

    @Override
    public HashMap<String, Object> getGroupDetail(String courseId) {
        Course course = courseRepository.getCourseByCourseId(courseId);
        Group group = course.getGroup();

        HashMap<String, Object> hashMap = new HashMap<>();

        hashMap.put("courseId", courseId);
        hashMap.put("groupId", courseId);
        hashMap.put("groupNotice", group.getNotice());
        hashMap.put("groupDescription", group.getDescription());

        return hashMap;
    }

    @Override
    public void updateGroup(String courseId, String groupNotice, String groupDescription) {
        String userIdWithType = tokenService.getCurrentUser();
        if (!userIdWithType.substring(0, 7).equalsIgnoreCase("teacher")) {
            throw GuliException.from("权限不足！");
        }
        Teacher teacher = teacherRepository.getByUserId(userIdWithType.substring(9));
        Group group = groupRepository.getGroupByGroupId(courseId);
        Course course = courseRepository.getCourseByCourseId(courseId);
        if (group == null)
            throw GuliException.from("圈子不存在");
        if (course.getTeacher() != teacher) {
            throw GuliException.from("权限不足！");
        }
        System.out.println("更新圈子信息 id:" + courseId + " Notice:" + groupNotice + " description: " + groupDescription);
        group.setNotice(groupNotice);
        group.setDescription(groupDescription);
        groupRepository.saveAndFlush(group);
    }
}
